// src/store/modules/user.ts
import { defineStore } from 'pinia'
import router from '@/router'
import { ElMessage } from 'element-plus'

// API 模块
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
    loginFormData,
    loginResponseData, userInfoReponseData,
} from '@/api/user/type'

// 工具
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import cloneDeep from 'lodash/cloneDeep'

// 状态类型
import type { UserState } from './type/type'
import {constantRoute} from "@/router/routes.ts";

/**
 * 过滤当前用户能访问的异步路由
 */
function filterAsyncRoute(asyncRoutes: any[], userRoutes: string[]): any[] {
    return asyncRoutes.filter((route) => {
        if (userRoutes.includes(route.name)) {
            if (route.children && route.children.length > 0) {
                route.children = filterAsyncRoute(route.children, userRoutes)
            }
            return true
        }
        return false
    })
}

const useUserStore = defineStore('User', {
    state: (): UserState => ({
        accessToken: GET_TOKEN(),
        menuRoutes: constantRoute, //仓库存储生成菜单需要数组(路由)
        username: '',
        avatar: '',
        id :null,
    }),

    actions: {
        /**
         * 登录方法
         */
        async userLogin(data: loginFormData) {
            try {
                const result: loginResponseData = await reqLogin(data)
                if (result.code === 200) {
                    this.accessToken = result.data.accessToken as string
                    SET_TOKEN(this.accessToken)
                    ElMessage.success('登录成功')
                    return 'ok'
                } else {
                    ElMessage.error(result.msg || '登录失败')
                    return Promise.reject(new Error(result.msg))
                }
            } catch (err: any) {
                ElMessage.error(err.message || '登录请求异常')
                return Promise.reject(err)
            }
        },

        /**
         * 获取用户信息
         */
        async userInfo() {
            try {
                const result: userInfoReponseData = await reqUserInfo()
                if (result.code === 200) {
                    const { name, avatar, buttons, routes } = result.data
                    this.username = name
                    this.avatar = avatar
                    return 'ok'
                } else {
                    ElMessage.error(result.msg || '获取用户信息失败')
                    return Promise.reject(new Error(result.msg))
                }
            } catch (err: any) {
                ElMessage.error(err.message || '用户信息请求异常')
                return Promise.reject(err)
            }
        },

        /**
         * 退出登录
         */
        async userLogout() {
            try {
                const result = await reqLogout()
                if (result.code === 200) {
                    this.resetUserState()
                    ElMessage.success('退出成功')
                    return 'ok'
                } else {
                    ElMessage.error(result.message || '退出失败')
                    return Promise.reject(new Error(result.message))
                }
            } catch (err: any) {
                ElMessage.error('退出请求异常')
                return Promise.reject(err)
            }
        },

        /**
         * 重置用户状态（退出或 token 失效时调用）
         */
        resetUserState() {
            this.accessToken = ''
            this.username = ''
            this.avatar = ''
            REMOVE_TOKEN()
            router.push('/login')
        },
    },
})

export default useUserStore
